/*
 * JBeagle - a Java toolkit for genetic algorithms.
 * 
 * Copyright (c) 2010 Matthijs Snel
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package jbeagle.core.ops;

import java.util.Collections;

import org.apache.log4j.Logger;

import jbeagle.concurrent.server.DefaultEvaluationManager;
import jbeagle.core.Individual;
import jbeagle.core.Population;

public class ElitistOperator<I extends Individual<G>, G> implements GeneticOperator<I, G> {

	static Logger log = Logger.getLogger(ElitistOperator.class);
	
	protected GeneticOperator<I, G> operator;
	protected int numToRetain;
	
	public ElitistOperator( GeneticOperator<I, G> o, int numToRetain) {
		operator = o;
		this.numToRetain = numToRetain;
	}
	
	@Override
	public Population<I, G> apply( Population<I, G> pop ) {
		Individual[] elites = new Individual[numToRetain];
		log.debug("Preventing modification of the best " + numToRetain + " individuals by " + operator.getClass());
		Collections.sort(pop);
		for ( int i = 0; i < numToRetain; i++ )
			elites[i] = pop.get(i);
		
		Population<I, G> nextPop = operator.apply(pop);
		
		int pos;
		for ( int i = 0; i < numToRetain; i++ ) {
			pos = (int) Math.round(Math.random() * (pop.size()-1));
			nextPop.set(pos, (I) elites[i]); 
		}
		return nextPop;
	}

	@Override
	public double getRate() {
		throw new UnsupportedOperationException();
	}

	@Override
	public void setRate(double r) {
		throw new UnsupportedOperationException();
	}

}
